package com.yongcheon.sms_manager.data.phone_spsm;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.yongcheon.sms_manager.data.preference.SpamNumberData;
import com.yongcheon.sms_manager.database.SpamDBManager;
import com.yongcheon.sms_manager.vo.PhoneVO;
import com.yongcheon.sms_manager.vo.SpamNumVO;

import java.util.ArrayList;

/**
 * Created by yongcheon on 2014-12-29.
 */
public class PhoneSpamData {

    public static void registAllSpam(Context context, SpamNumVO spamNumVO){
        PhoneData phoneData = new PhoneData();
        ArrayList<PhoneVO> smsList = phoneData.select(spamNumVO.getAddress(), context, null);
        registSpam(smsList, spamNumVO, context);
    }
    //
    public static void registSpam(ArrayList<PhoneVO> aList, SpamNumVO spamNumVO, Context context){
        PhoneData phoneData = new PhoneData();
        SQLiteDatabase database = SpamDBManager.getDatabase(context);
        SpamNumberData spamNumData = new SpamNumberData(context);
        SpamPhonData spamPhonData = new SpamPhonData();

        try {
            database.beginTransaction();

            for (int i = 0; i < aList.size(); i++) {
                PhoneVO vo = aList.get(i);
                vo.setSpam_category(spamNumVO.getCategory_2());
                vo.setSpam_desc(spamNumVO.getSubject());
                spamPhonData.insert(aList.get(i), context, database);
            }

            spamNumData.insertNotExist(spamNumVO, context, database);

            for (int i = 0; i < aList.size(); i++) {
                phoneData.delete(aList.get(i).getId(), context,  null);
            }

            database.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            database.endTransaction();
        }
    }

    public static void unRegistSpam(SpamNumVO spamNumVO, Context context){
        PhoneData phoneData = new PhoneData();
        SQLiteDatabase database = SpamDBManager.getDatabase(context);
        SpamNumberData spamNumData = new SpamNumberData(context);
        SpamPhonData spamPhonData = new SpamPhonData();

        try {
            database.beginTransaction();

            ArrayList<PhoneVO> aList = spamPhonData.select(spamNumVO.getAddress(), context, database);

            for (int i = 0; i < aList.size(); i++) {
                spamPhonData.delete(aList.get(i).getId(), context, database);
            }

            for (int i = 0; i < aList.size(); i++) {
                phoneData.insert(aList.get(i), context, null);
            }

            spamNumData.delete(spamNumVO.getAddress(), context, database);

            database.setTransactionSuccessful();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            database.endTransaction();
        }
    }
}
